package com.dungnt.vtime.countdown;

import android.animation.Animator;
import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.animation.Animator.AnimatorListener;
import android.animation.ValueAnimator.AnimatorUpdateListener;
import android.app.Activity;
import android.app.Fragment;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Bundle;
import android.util.Log;
import android.view.ContextThemeWrapper;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.dungnt.vtime.R;
import com.dungnt.vtime.VTSetCountdownTime;
import com.dungnt.vtime.common.cls.VLog;
import com.dungnt.vtime.customview.HoloCircularProgressBar;
import com.dungnt.vtime.utils.Constant;
import com.dungnt.vtime.utils.Utils;

public class VTCountDownFragment extends Fragment implements OnClickListener {

	private static final int SET_TIME = 1; // request code ( used in
											// onActivityResult )

	private View v;
	private Button btnStart, btnReset;
	private boolean isStarting, isPausing;
	private TextView tvTimeRemain;
	private Typeface mFont;
	private LinearLayout mCreateTimer, mCountdownController, mEmptyDataLayout;
	private FrameLayout mCountdownTimeView;
	private HoloCircularProgressBar mTimeProgressBar;
	private int hrs, mins, secs;
	private VTCountDownItem c;
	private VTCountDownTimer vCountDown;
	private ObjectAnimator mProgressBarAnimator;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		final Context contextThemeWrapper = new ContextThemeWrapper(
				getActivity(), R.style.BookmarkTheme);
		LayoutInflater localInflater = inflater
				.cloneInContext(contextThemeWrapper);
		v = localInflater
				.inflate(R.layout.countdown_fragment, container, false);
		return v;
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onActivityCreated(savedInstanceState);
		mFont = Utils.getFontFromAssets(getActivity(), Constant.TIME_FONT);
		mCreateTimer = (LinearLayout) v.findViewById(R.id.header_add_bookmark);
		mCountdownController = (LinearLayout) v
				.findViewById(R.id.countdown_controller);
		mCountdownTimeView = (FrameLayout) v
				.findViewById(R.id.countdown_timeview);
		mEmptyDataLayout = (LinearLayout) v
				.findViewById(R.id.coutdown_empty_layout);

		tvTimeRemain = (TextView) v.findViewById(R.id.countdown_tvTimeRemain);
		tvTimeRemain.setTypeface(mFont);
		mTimeProgressBar = (HoloCircularProgressBar) v
				.findViewById(R.id.countdown_timeProgress);
		mTimeProgressBar.setProgress(0);
		mCreateTimer.setOnClickListener(this);
		btnStart = (Button) v.findViewById(R.id.countdown_btnStart);
		btnStart.setOnClickListener(this);
		btnReset = (Button) v.findViewById(R.id.countdown_btnReset);
		btnReset.setOnClickListener(this);
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		if (v == btnStart) {
			if (!isStarting && !isPausing) {
				startCountDown(c);
			} else if (isStarting) {
				pauseCountDown();
			} else if (isPausing) {
				resumeCountDown();
			}

		} else if (v == mCreateTimer) {
			Intent i = new Intent(getActivity(), VTSetCountdownTime.class);
			startActivityForResult(i, SET_TIME);
		} else if (v == btnReset) {
			resetCountdown();
		}
	}

	private void resetCountdown() {
		vCountDown.cancel();
		tvTimeRemain.setText("" + hrs + ":" + mins + ":" + secs);
		isPausing = false;
		isStarting = false;
		btnStart.setText(getActivity().getString(R.string.start_btn));
		mProgressBarAnimator.cancel();
		mProgressBarAnimator.end();
		mTimeProgressBar.setProgress(0);
	}

	private void resumeCountDown() {
		btnStart.setText(getActivity().getString(R.string.pause_btn));
		isPausing = false;
		isStarting = true;
		long remainMill = vCountDown.getRemainMilli();
		vCountDown = new VTCountDownTimer(remainMill,
				Constant.COUNTDOWN_INTERVAL);
		vCountDown.setV(tvTimeRemain);

		vCountDown.start();
		animate(mTimeProgressBar, null, mTimeProgressBar.getProgress(), 1f,
				(int) remainMill);
	}

	private void pauseCountDown() {
		// TODO Auto-generated method stub
		VLog.D("Paused");
		vCountDown.cancel();
		mProgressBarAnimator.cancel();
		VLog.D("Time: " + mTimeProgressBar.getProgress());
		btnStart.setText(getActivity().getString(R.string.resume_btn));
		isPausing = true;
		isStarting = false;
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		if (resultCode == Activity.RESULT_OK && requestCode == SET_TIME) {
			setTime(data);
		}
	}

	private void showTimeView(boolean isEnable) {
		if (isEnable) {
			mCreateTimer.setVisibility(View.GONE);
			mEmptyDataLayout.setVisibility(View.GONE);
			mCountdownController.setVisibility(View.VISIBLE);
			mCountdownTimeView.setVisibility(View.VISIBLE);
		} else {
			mCreateTimer.setVisibility(View.VISIBLE);
			mEmptyDataLayout.setVisibility(View.VISIBLE);
			mCountdownController.setVisibility(View.GONE);
			mCountdownTimeView.setVisibility(View.GONE);
		}
	}

	private void setTime(Intent data) {
		// TODO Auto-generated method stub
		showTimeView(true);
		hrs = data.getIntExtra("hours", 0);
		mins = data.getIntExtra("minutes", 0);
		secs = data.getIntExtra("seconds", 0);
		tvTimeRemain.setText("" + hrs + ":" + mins + ":" + secs);
		c = new VTCountDownItem(0, hrs, mins, secs, 0); // default day = 0,
														// ringTone = 0;
	}

	private void startCountDown(VTCountDownItem c) {
		// TODO Auto-generated method stub
		vCountDown = new VTCountDownTimer(c, Constant.COUNTDOWN_INTERVAL,
				tvTimeRemain);
		vCountDown.start();

		if (mProgressBarAnimator != null) {
			mProgressBarAnimator.cancel();
		}
		animate(mTimeProgressBar, null, 0f, 1f, (int) c.toMiliseconds());
		mTimeProgressBar.setProgressColor(Color.CYAN);
		btnStart.setText(getActivity().getString(R.string.pause_btn));
		isStarting = true;
		isPausing = false;
	}

	private void animate(final HoloCircularProgressBar progressBar,
			final AnimatorListener listener, final float progressFrom,
			final float progressTo, final int duration) {

		mProgressBarAnimator = ObjectAnimator.ofFloat(progressBar, "progress",
				progressFrom, progressTo);
		mProgressBarAnimator.setDuration(duration);

		mProgressBarAnimator.addListener(new AnimatorListener() {

			@Override
			public void onAnimationCancel(final Animator animation) {
				// VLog.D("Cancel animation");
				// progressBar.setProgress(currentProgress);
			}

			@Override
			public void onAnimationEnd(final Animator animation) {
				progressBar.setProgress(progressBar.getProgress());
				if (progressBar.getProgress() == 1f) {
					btnStart.setText(getActivity()
							.getString(R.string.start_btn));
				}
			}

			@Override
			public void onAnimationRepeat(final Animator animation) {
			}

			@Override
			public void onAnimationStart(final Animator animation) {
			}
		});
		if (listener != null) {
			mProgressBarAnimator.addListener(listener);
		}
		// mProgressBarAnimator.reverse();
		mProgressBarAnimator.addUpdateListener(new AnimatorUpdateListener() {

			@Override
			public void onAnimationUpdate(final ValueAnimator animation) {
				progressBar.setProgress((Float) animation.getAnimatedValue());
			}
		});
		progressBar.setMarkerProgress(progressTo);
		mProgressBarAnimator.start();
	}
}
